/*
 * @Author: your name
 * @Date: 2019-11-01 10:17:50
 * @LastEditTime: 2019-11-08 16:00:18
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \koa-example\src\controllers\public.js
 */

//引入node-xlsx解析excel模块
const fs = require('fs');
const path = require("path");
const node_xlsx = require('node-xlsx');
const { questionGenerateApi } = require('../../api/question');
const { questionListRandomByCount } = require('../../api/question');

// 更新题库
async function questionsGennerateController() {

  // 解析导入的excel
  path.resolve(__dirname, '../../')
  var files = fs.readdirSync(path.join(__dirname, '../../static/questionBank'))

  let insertData = [];//存放数据
  files.forEach( (item, index) => {
    let obj = node_xlsx.parse(fs.readFileSync(path.join(__dirname, `../../static/questionBank/${item}`)));// 支持的excel文件类有.xlsx .xls .xlsm .xltx .xltm .xlsb .xlam等
    // console.log(obj)
    let excelObj = obj[0].data;//取得第一个excel表的数据
  
    //循环遍历表每一行的数据
    for (var i = 1; i < excelObj.length; i++) {
      var rdata = excelObj[i];
      for (var j = 0; j < rdata.length; j++) {
        insertData.push({question_name:rdata[0], options:[rdata[1],rdata[2],rdata[3],rdata[4]], answer:rdata[5], type:index})
      }
      
    }
  })

  // result
  let result = await questionGenerateApi(insertData);
  return {
    success: true,
    data: result.length
  }

  // //导入解析成功后 将文件删除
  // fs.unlink(excelConfig.excel_Dir, function (err) {
  //   if (err) throw err;
  //   console.log("删除文件" + excelConfig.excel_Dir + "成功")
  // })

  function getRandomArrayElements(arr, count) {
    var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
  }
}


async function questionsListControllerByCount(count) {
  let result = await questionListRandomByCount(count)
  return result
}

module.exports = {
  questionsGennerateController,
  questionsListControllerByCount
}